package team.fourth.combat.web;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import team.fourth.combat.commen.constant.RedisConstant;
import team.fourth.combat.commen.entity.Result;
import team.fourth.combat.commen.utils.RedisUtil;
import team.fourth.combat.pojo.Member;
import team.fourth.combat.service.MemberService;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/login")
public class LoginController {
    //spring容器一定要有这个实例（使用bean标签可以创建对象，在类上加注解然后使用扫描）
    @Autowired
    RedisUtil redisUtil;
    @Reference
    MemberService memberService;

    @RequestMapping("/check")
    public Result check(@RequestBody Map map, HttpServletRequest request){
        String telephone =  (String)map.get("telephone");
        String validateCode =  (String)map.get("validateCode");
//            1、校验验证码
        String redisCode = redisUtil.get(telephone + RedisConstant.SENDTYPE_LOGIN);

        /** if(null == redisCode){
            return Result.error("验证码错误");
        }

        if(!redisCode.equals(validateCode)){
            return Result.error("验证码错误");
        }*/

        if(null == redisCode || !redisCode.equals(validateCode)){
            return Result.error("验证码错误");
        }

//            2、根据手机号码查询会员表是否存在对应的用户信息
        Member member = memberService.findByTelephone(telephone);
//            3、如果不存在就自动注册
        if(null == member){
            member = new Member();
            member.setPhoneNumber(telephone);
            member.setRegTime(new Date());
            member = memberService.add(member);
        }
//            4、把用户信息存入session（用户下次调用接口需要先判断session是否有对应用户信息，如果没有那就要跳转到登录页面）

//        request.getSession().setAttribute("member",member);

        //现在把用户信息存入redis，mysql
        String token = UUID.randomUUID().toString();
        redisUtil.setex(token, JSON.toJSONString(member),60 * 60 * 24 * 15);
        return Result.success("登录成功",token);
    }
}
